import sys
from datetime import datetime
from enum import Enum
from pathlib import Path
from typing import Any, Dict, List

from loguru import logger
from pydantic import BaseModel, field_validator
from pydantic_settings import BaseSettings


class LogLevel(str, Enum):
    DEBUG = "DEBUG"
    INFO = "INFO"


class LogSettings(BaseSettings):
    # 日志配置
    log_level: str = LogLevel.INFO.value
    rotation: str = "00:00"
    retention: str = "7 days"
    ansi_color: bool = True
    log_format: str = (
        "<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{module}.{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
    )
    dynamic_list: List[str] = ["pass", "key", "secret"]


log_settings = LogSettings()


class LogConfig(BaseModel):
    """日志配置"""

    rotation: str
    retention: str
    log_level: str
    ansi_color: bool
    log_format: str
    dynamic_list: List[str]
    log_path: Path = Path("logs") / f"{datetime.now():%Y-%m-%d}.log"

    @field_validator("log_path")
    def validate_log_path(cls, v: Path) -> Path:
        v.parent.mkdir(parents=True, exist_ok=True)
        return v


class EnhancedLogger:
    """增强的日志记录器"""

    def __init__(self, config: LogConfig) -> None:
        self.config = config
        self.logger = self._init_logger()

    def _init_logger(self) -> Any:
        """初始化日志记录器"""
        logger.remove()

        # 日志配置字典
        cfg_map = {
            "format": self.config.log_format,
            "level": self.config.log_level,
            "filter": self._dynamic_filter,
            "enqueue": True,
            "backtrace": True,
            "diagnose": True,
        }

        # 添加控制台日志输出
        logger.add(sys.stderr, colorize=self.config.ansi_color, **cfg_map)

        # 添加文件日志输出
        logger.add(
            sink=self.config.log_path,
            rotation=self.config.rotation,
            retention=self.config.retention,
            **cfg_map,
        )

        return logger

    def _dynamic_filter(self, record: Dict) -> bool:
        """过滤不需要的日志消息"""

        return not any(
            msg in record["message"].lower() for msg in self.config.dynamic_list
        )


config = LogConfig(**log_settings.model_dump())
log = EnhancedLogger(config=config)
mylogger = log.logger
